<template >
  <div class="login_container">
    <div class="login_box">
      <div class="head_logo">
        <img src="..\assets\logo.png" alt="" />
      </div>

      <!-- 登录表单区域 -->
      <el-form
        ref="loginFormRef"
        label-width="0px"
        class="login_form"
        :rules="loginFormRules"
        :model="loginForm"
      >
        <el-form-item prop="username">
          <el-input
            placeholder="请输入用户名"
            v-model="loginForm.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            placeholder="请输入密码"
            v-model="loginForm.password"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="success" @click="submitForm">登录</el-button>
          <el-button type="info" @click="resetForm">重置</el-button>
          <el-button type="primary" @click="addDialogVisible = true"
            >注册</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <!-- 用户注册窗口 -->
    <el-dialog
      title="用户注册"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 正文区域 -->
      <el-form
        :rules="loginFormRules"
        ref="addFormRef"
        :model="user"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username" placeholder="用户名必须是3~10位,以字母开头"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="user.password" show-password placeholder="密码必须是6~15位,以字母开头"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPassword">
          <el-input
            type="password"
            v-model="user.checkPassword"
            placeholder="密码必须是6~15位,以字母开头"
            show-password
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="user.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="mobile">
          <el-input v-model="user.mobile" placeholder="请输入联系电话"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="add()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    //验证用户名的规则
    var validateUser = (rule, value, callback) => {
      let un = /^[A-Za-z]+\w{2,9}$/;
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else {
        //密码长度为6~15位
        if (un.test(value)) {
          callback();
        } else {
          callback(new Error("用户名格式不正确!"));
        }
      }
    };
    var checkEmail = (rule, value, callback) => {
      let reg = /^\w+@[A-Za-z\d]{2,3}\.[a-zA-Z]{2,3}([a-zA-Z]{2,3})?$/;
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的邮箱.."));
      }
    };
    //再次输入密码规则
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.user.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    //验证密码的规则
    // var validatePass = (rule, value, callback) => {
    //   let un = /^[A-Za-z]+\w{5,14}$/;
    //   if (value === "") {
    //     callback(new Error("请输入密码"));
    //   } else {
    //     //密码长度为6~15位
    //     if (un.test(value)) {
    //       callback();
    //     } else {
    //       callback(new Error("密码格式不正确!"));
    //     }
    //   }
    // };
    //验证手机号的规则
    var validatePhone = (rule, value, callback) => {
       let phone = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else {
        //密码长度为6~15位
        if (phone.test(value)) {
          callback();
        }else{
           callback(new Error("用户名格式不正确!"));
        }
      }
    };
    return {
      addDialogVisible: false, //控制添加窗口的显示和隐藏
      user: {}, //存储用户对象

      // 登录的表单数据绑定对象
      loginForm: {},
      // 表单验证规则对象
      loginFormRules: {
        // 设置验证规则的名称
        username: [
          {
            required: true, //必填项
            message: "请输入用户名", //错误后提示消息
            trigger: "blur", //当光标离开的时候触发，默认值是blur
          },
          {
            validator: validateUser,
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            min:6,
            max:15,
            message:'请输入6-15位的密码',
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          // 调用自定义验证规则
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          { validator: validatePhone, trigger: "blur" },
        ],
        checkPassword: [
          {
            required: true,
            message: "请输入确认密码",
            trigger: "blur",
          },
          {
            validator: validatePass2,
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    submitForm() {
      console.log("登录");
      //登录前先判断是否符合验证规则，当满足后向后台提交数据
      //validate() 触发指定表单的验证规则
      this.$refs.loginFormRef.validate((valid) => {
        if (valid) {
          this.$http
            .get(
              `users?username=${this.loginForm.username}&password=${this.loginForm.password}`
            )
            .then((result) => {
              if (result.data.length) {
                //开启加载动画
                let loading = this.$loading({
                  text: "登录成功...正在加载中...",
                });
                console.log("登录成功..");
                this.$message.success("登录成功^_^..");
                // 将用户存储到sessionStorage中
                window.sessionStorage.setItem(
                  "token",
                  JSON.stringify(result.data[0])
                );
                //速度会快一点
                let timer = setInterval(() => {
                  if (window.sessionStorage.getItem("token")) {
                    loading.close(); //关闭加载动画
                    this.$router.push("/home"); //跳转路由
                    clearInterval(timer);
                  }
                }, 500);
                //速度稍慢
                // setTimeout(() => {
                //   loading.close(); //关闭加载动画
                //   this.$router.push("/home"); //跳转路由
                // }, 2000);
              } else {
                console.log("登录失败..");
                this.$message.error("登录失败=_=..");
              }
            })
            .catch((err) => {
              console.log(err);
            });
        }
      });
    },
    resetForm() {
      this.$refs.loginFormRef.resetFields();
    },
    addDialogClosed() {
      //使用引用表单名称重置表单
      this.$refs.addFormRef.resetFields();
    },

    // 添加用户
    add() {
      //判断验证规则
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return false;
        this.$http.post("users", this.user).then((res) => {
          if (res.status !== 201) {
            this.$message.error("用户添加失败...");
          } else {
            this.$message.success("用户添加成功...");
          }
          this.addDialogVisible = false;
        });
      });
    },
  },
};
</script>
<style lang="less" scoped>
.login_container {
  //   background: #2b4b6b;
  //   background: linear-gradient(blue, pink); //渐变色
  background-image: linear-gradient(120deg, #d4fc79 0%, #96e6a1 100%);
  height: 100%;
  .login_box {
    width: 450px;
    height: 300px;
    background-image: linear-gradient(120deg, #f6d365 0%, #fda085 100%);
    border-radius: 5px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    .head_logo {
      height: 130px;
      width: 130px;
      border: 1px solid #ccc;
      border-radius: 50%;
      padding: 10px;
      box-shadow: 0 0 10px #ddd;
      position: absolute;
      left: 50%;
      transform: translate(-50%, -50%);
      //   background: #fff;
      background-image: linear-gradient(to top, #cfd9df 0%, #e2ebf0 100%);
      img {
        width: 100%;
        height: 100%;
        // border-radius: 100%;
      }
    }
  }
  .login_form {
    position: absolute;
    bottom: 0px;
    width: 100%;
    padding: 0px 20px;
    /*
      指定宽度和高度，确定元素的边框
      也就是说，对元素指定宽度和高度包括了padding和border
      */
    box-sizing: border-box;

    .btns {
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>